<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class IpSource extends Command
{
    protected function configure()
    {
        $this->setName('ip_source')->setDescription('IP统计');
    }

    protected function execute(Input $input, Output $output)
    {
        $ipLocation = Cache::store('redis')->handler()->keys('STAT:USER_IP_SOURCE:*') ?: [];
        $province = ["北京", "上海", "天津", "重庆", "浙江", "江苏", "广东", "福建", "湖南", "湖北", "辽宁",
            "吉林", "黑龙江", "河北", "河南", "山东", "陕西", "甘肃", "新疆", "青海", "山西", "四川",
            "贵州", "安徽", "江西", "云南", "内蒙古", "西藏", "广西", "宁夏", "海南", "香港", "澳门", "台湾"
        ];

        $data = [
            "北京" => 0, "上海" => 0, "天津" => 0, "重庆" => 0, "浙江" => 0, "江苏" => 0, "广东" => 0, "福建" => 0, "湖南" => 0,
            "湖北" => 0, "辽宁" => 0, "吉林" => 0, "河北" => 0, "河南" => 0, "山东" => 0, "陕西" => 0, "甘肃" => 0, "西藏" => 0,
            "新疆" => 0, "青海" => 0, "山西" => 0, "四川" => 0, "贵州" => 0, "安徽" => 0, "江西" => 0, "云南" => 0, "内蒙古" => 0,
            "广西" => 0, "宁夏" => 0, "海南" => 0, "香港" => 0, "澳门" => 0, "台湾" => 0, "黑龙江" => 0, '南海诸岛' => 0
        ];

        //
        foreach ($ipLocation as $ip) {
            if (!$ip = ltrim($ip, 'STAT:USER_IP_SOURCE:')) {
                continue;
            }
            if (in_array($ip, ['127.0.0.1', '0.0.0.0'])) {
                continue;
            }
            usleep(mt_rand(5000, 10000));
            try {
                $res = file_get_contents("https://www.ipshudi.com/{$ip}.htm");
                preg_match("/归属地<\/td>[\W|\w|\d|\D|\S|\s]{5,200}(?=<\/span>)/siU", $res, $matches);
                if (empty($matches[0])) {
                    continue;
                }

                $string = ltrim($matches[0], '归属地');
                $string = str_replace("\n", '', $string);
                $string = strip_tags($string);
                $array = explode(' ', $string);

                if (!empty($array[0])) {
                    if (in_array($array[1], $province)) {
                        $data[$array[1]]++;
                    } else {
                        $data['南海诸岛']++;
                    }
                }

            } catch (\Exception $exception) {

            }
        }

        Cache::set('ip_source', $data);

        $output->writeln("执行成功");
    }
}